package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.enums.FlowTypeEnum;
import com.rongke.model.*;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import com.rongke.utils.RandomUtils;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version : Ver 1.0
 * @ExperienceRecommendController
 * @体验推荐Controller
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/api/experienceRecommend")
@Transactional
public class ExperienceRecommendController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private ExperienceRecommendService experienceRecommendService;
    @Autowired
    private ExpRecCommentService expRecCommentService;
    @Autowired
    private MuserService muserService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private FlowDetailService flowDetailService;
    @Autowired
    private CacheUtil cacheUtil;

    /**
     * @param experienceRecommend
     * @return 返回值JsonResp
     * @添加体验推荐
     */
    @RequestMapping(value = "/addRecommend", method = RequestMethod.POST)
    public JsonResp addExperienceRecommend(@RequestBody ExperienceRecommend experienceRecommend) {
        log.debug("添加体验推荐");
        experienceRecommend.setGmtDatetime(new Date());
        experienceRecommendService.insert(experienceRecommend);
        return JsonResp.ok(experienceRecommend);
    }

    /**
     * @param experienceRecommend
     * @return 返回值JsonResp
     * @修改
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateFind(@RequestBody ExperienceRecommend experienceRecommend) {
        log.debug("修改");
        experienceRecommend.setUptDatetime(new Date());
        experienceRecommendService.updateById(experienceRecommend);
        return JsonResp.ok(experienceRecommend);
    }

    /**
     * 删除体验推荐
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delExp", method = RequestMethod.GET)
    public JsonResp delExp(Long id) {
        log.debug("删除体验推荐");
        experienceRecommendService.deleteById(id);
        return JsonResp.ok("删除成功");
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找体验推荐
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectExperienceRecommend(Long id) {
        log.debug("查找体验推荐");
        ExperienceRecommend experienceRecommend = experienceRecommendService.selectById(id);
        return JsonResp.ok(experienceRecommend);
    }

    /**
     * @return
     * @获取体验推荐列表
     */
    @RequestMapping(value = "/selectExperienceRecommendList", method = RequestMethod.GET)
    public JsonResp selectExperienceRecommendList(Page page) {
        log.debug("获取体验推荐列表");
        EntityWrapper<ExperienceRecommend> ew = new EntityWrapper<>();
        //选取审核通过状态为1（即已审核已通过）的体验推荐
        ew.eq("check_status", 1);
        ew.orderBy("is_up", false);
        ew.orderBy("gmt_datetime", false);
        Page<ExperienceRecommend> recommendPage = experienceRecommendService.selectPage(page, ew);
        recommendPage.getRecords().forEach(e -> {
            Integer thumbNum = 0;
            if (cacheUtil.hasKey("exp_rec" + e.getId())) {
                Set thumb = cacheUtil.getSet("exp_rec" + e.getId());
                thumbNum = thumb.size();
            }
            e.setThumbsNum(thumbNum);
            EntityWrapper<ExpRecComment> ewc = new EntityWrapper<>();
            ewc.eq("er_id", e.getId());
            e.setCommentNum(expRecCommentService.selectCount(ewc));
        });
        return JsonResp.ok(recommendPage);
    }

    /**
     * @return
     * @获取某个体验推荐详情
     */
    @RequestMapping(value = "/selectExperienceDetail", method = RequestMethod.GET)
    public JsonResp selectExperienceDetail(Long muserId, Long id) {
        log.debug("获取某个体验推荐详情");
        if (null == id)
            return JsonResp.toFail("参数不能为空");
        ExperienceRecommend experienceRecommend = experienceRecommendService.selectExperienceDetail(id);
        if (StringUtil.isNotEmpty(experienceRecommend.getGoodsId())) {
            List<Goods> goodsList = new ArrayList<>();
            String[] goodsIds = experienceRecommend.getGoodsId().split(",");
            for (String goodsId : goodsIds) {
                Goods g = goodsService.selectById(goodsId);
                if (null != g) {
                    goodsService.fetchGoodsInventoryStatus(g);
                    goodsList.add(g);
                }
            }
            experienceRecommend.setGoodsList(goodsList);
        }
  /*      if (experienceRecommend.getUser().getUserName().length() > 1) {
            String origName = experienceRecommend.getUser().getUserName();
            StringBuffer nameSB = new StringBuffer(origName);
            nameSB.replace(1, 2, "*");
            experienceRecommend.getUser().setUserName(nameSB.toString());
        }*/
        String origName = experienceRecommend.getUser().getPhone();
        StringBuffer nameSB = new StringBuffer(origName);
        nameSB.replace(0, 7, "*******");
        experienceRecommend.getUser().setUserName(nameSB.toString());
        EntityWrapper<ExpRecComment> ewc = new EntityWrapper<>();
        ewc.eq("er_id", experienceRecommend.getId());
        experienceRecommend.setCommentNum(expRecCommentService.selectCount(ewc));
        Integer isThumb = 0;
        Integer thumbNum = 0;
        if (cacheUtil.hasKey("exp_rec" + id)) {
            Set thumb = cacheUtil.getSet("exp_rec" + id);
            thumbNum = thumb.size();
            if (thumb.contains(muserId.toString())) {
                isThumb = 1;
            }
        }
        experienceRecommend.setIsThumb(isThumb);//是否已点赞
        experienceRecommend.setThumbsNum(thumbNum);//点赞量
        return JsonResp.ok(experienceRecommend);
    }

    /**
     * 体验推荐点赞
     *
     * @param muserId
     * @param erId
     * @return
     */
    @RequestMapping(value = "/thumbRecArticle", method = RequestMethod.GET)
    public JsonResp thumbRecArticle(Long muserId, Long erId) {
        log.debug("体验推荐点赞");
        if (null == erId || null == muserId)
            return JsonResp.toFail("参数为空");
        if (cacheUtil.hasKey("exp_rec" + erId)) {
            Set thumb = cacheUtil.getSet("exp_rec" + erId);
            thumb.add(muserId.toString());
            cacheUtil.addSet("exp_rec" + erId, muserId.toString());
        } else {
            Set newthumb = new HashSet();
            newthumb.add(muserId);
            cacheUtil.addSet("exp_rec" + erId, muserId.toString());
        }
        Map map = new HashMap();
        Set thumb = cacheUtil.getSet("exp_rec" + erId);
        map.put(erId, thumb);
/*        if(cacheUtil.hasKey("exp_rec"+12)){
            cacheUtil.removeFromSet("exp_rec"+12,"ewFt");
            Set set=cacheUtil.getSet("exp_rec"+12);
            System.out.println(set);
            set.add(RandomUtils.getRandomString(4));
            cacheUtil.addSet("exp_rec"+12,RandomUtils.getRandomString(4));
        }else{
            cacheUtil.addSet("exp_rec"+12,"222","33");
        }*/
        return JsonResp.ok(thumb);
    }

    /**
     * @param id
     * @return
     * @获取某条推荐的评论列表
     */
    @RequestMapping(value = "/getExpRecCommentsByRecId", method = RequestMethod.GET)
    public JsonResp getExpRecCommentsByRecId(Long id, Page page) {
        EntityWrapper<ExpRecComment> ew = new EntityWrapper<>();
        ew.eq("er_id", id);
        Page<ExpRecComment> expRecCommentPage = expRecCommentService.selectPage(page, ew);
        expRecCommentPage.getRecords().forEach(e -> {
            Muser muser = muserService.selectById(e.getMuserId());
            if (null != muser) {
                e.setUserName(muser.getUserName());
                e.setAvatarUrl(muser.getAvatarUrl());
                e.setMemberLevel(muser.getMemberLevel());
            }
        });
        return JsonResp.ok(expRecCommentPage);
    }

    /**
     * @return
     * @后台获取体验推荐列表
     */
    @RequestMapping(value = "/selectNotList", method = RequestMethod.GET)
    public JsonResp selectNotList(String title, Integer checkStatus) {
        log.debug("后台获取体验推荐列表");
        EntityWrapper<ExperienceRecommend> ew = new EntityWrapper<>();
        if (title != null && !"".equals(title)) {
            ew.like("title", title);
        }
        if (checkStatus != null && !"".equals(checkStatus)) {
            ew.eq("check_status", checkStatus);
        }
        ew.orderBy("gmt_datetime", false);
        List<ExperienceRecommend> list = experienceRecommendService.selectList(ew);
        for (ExperienceRecommend recommend : list) {
            recommend.setUser(muserService.selectById(recommend.getUserId()));
            if (StringUtil.isNotEmpty(recommend.getGoodsId())) {
                List<Goods> goodsList = new ArrayList<>();
                String[] goodsIds = recommend.getGoodsId().split(",");
                for (String goodsId : goodsIds) {
                    Goods g = goodsService.selectById(goodsId);
                    if (null != g) {
                        goodsList.add(g);
                    }
                }
                recommend.setGoodsList(goodsList);
            }

        }
        return JsonResp.ok(list);
    }

    /**
     * @param ids
     * @return
     * @一键审核通过
     */
    @RequestMapping(value = "/egisAll", method = RequestMethod.GET)
    public JsonResp egisAll(String ids) {
        String[] id = ids.split(",");
        EntityWrapper<ExperienceRecommend> ew = new EntityWrapper<>();
        ew.in("id", ids);
        List<ExperienceRecommend> list = experienceRecommendService.selectList(ew);
        for (ExperienceRecommend recommend : list) {
            recommend.setCheckStatus(1);
            recommend.setUptDatetime(new Date());
        }
        experienceRecommendService.updateBatchById(list);
        return JsonResp.ok();
    }


    /**
     * 审核通过 拒绝 申精 ，通过或加精后奖励雅币
     * @param rec
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public JsonResp updateExperienceRecommend(@RequestBody ExperienceRecommend rec) {
        log.debug("修改体验推荐");
        Long id = rec.getId();
        ExperienceRecommend entity = experienceRecommendService.selectById(id);

        Integer isHome = rec.getIsHome();
        Integer checkStatus = rec.getCheckStatus();
        if (entity != null) {
            if (entity.getCheckStatus() == 2 && checkStatus == 1) {
                //审核通过
                Account acc = accountService.selectAccountByUserId(entity.getUserId());
                Account newAcc = new Account();
                newAcc.setId(acc.getId());
                BigDecimal yabi = acc.getYaBi().add(new BigDecimal(5));
                newAcc.setYaBi(yabi);
                accountService.updateById(newAcc);
                //****************流水记录*******************//
                FlowDetail expBonus = new FlowDetail();
                expBonus.setGmtDatetime(new Date());
                expBonus.setMuserId(entity.getUserId());
                expBonus.setMoney(new BigDecimal(5));
                expBonus.setFlowType(FlowTypeEnum.EXPBONUS.getType());
                expBonus.setTitle("体验推荐审核通过奖励雅币" + 5);
                flowDetailService.insert(expBonus);
            }

//            体验推荐审核通过奖励5雅币，加精后奖励5雅币
            Integer bonusTag = entity.getIsRewarded();//0表示还未领取过奖励
            if (0 == bonusTag  && entity.getCheckStatus()== 1 && 1 == entity.getIsHome()) {
                rec.setIsRewarded(1);

                Account acc = accountService.selectAccountByUserId(entity.getUserId());
                Account newAcc = new Account();
                newAcc.setId(acc.getId());
                BigDecimal yabi = acc.getYaBi().add(new BigDecimal(5));
                newAcc.setYaBi(yabi);
                accountService.updateById(newAcc);
                //****************流水记录*******************//
                FlowDetail expBonus = new FlowDetail();
                expBonus.setGmtDatetime(new Date());
                expBonus.setMuserId(entity.getUserId());
                expBonus.setMoney(new BigDecimal(5));
                expBonus.setFlowType(FlowTypeEnum.EXPBONUS.getType());
                expBonus.setTitle("体验推荐审核加精奖励雅币" + 5);
                flowDetailService.insert(expBonus);
            }
            rec.setUptDatetime(new Date());
            experienceRecommendService.updateById(rec);
            return JsonResp.ok(rec);
        } else {
            return JsonResp.toFail("参数ID错误");
        }


    }

    /**
     * 获取某用户购买过的商品列表
     *
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/getHistoryPurchaseByUserId", method = RequestMethod.GET)
    public JsonResp getHistoryPurchaseByUserId(Long muserId) {
        log.debug("获取某用户购买过的商品列表,muserId=" + muserId);
        if (null == muserId || 0 == muserId) {
            return JsonResp.toFail("参数不能为空");
        }
        EntityWrapper<Orders> ew = new EntityWrapper<>();
        ew.setSqlSelect("id");
        ew.eq("muser_id", muserId);
        ew.in("order_status", Arrays.asList(4, 5));
        List orderIds = ordersService.selectObjs(ew);
        List<Goods> goodsList = new ArrayList<>();
        if (!orderIds.isEmpty()) {
            EntityWrapper<OrderGoods> ewg = new EntityWrapper<>();
            ewg.setSqlSelect("distinct(goods_id)");
            ewg.in("order_id", orderIds);
            List goodsIds = orderGoodsService.selectObjs(ewg);
            EntityWrapper<Goods> ewgd = new EntityWrapper<>();
            ewgd.eq("goods_status", 2);
            ewgd.in("id", goodsIds);
            goodsList = goodsService.selectList(ewgd);
        }
        return JsonResp.ok(goodsList);
    }

    public static void main(String[] args) {
        // 将字符串换成大写并用逗号链接起来
        List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.", "Canada");
        Collectors.joining(",");
        System.out.println("args = [" + args + "]");
    }
}
